import {
  login,
  getLocation,
  _getTokenSucc,
  getUserInfoSucc
} from '../../login/index'
import base from '../../api/base'
import {
  toast,
  distance
} from '../../utils/util'
const app = getApp()

Page({
  data: {
    key: base.subkey,
    tabIndex: 0,
    tableIndex: 0,
    list: [],
    scale: 0,
    markers: [],
    longitude: 104.324520,
    latitude: 35.099994,
    enterprise: [],
    freedate: '',
    equipment: '',
    code: ''
  },
  onLoad: function (options) {
    this.initRouter(this.route)
    this.checkSession(options)
  },
  initRouter(route) {
    wx.setStorageSync('router', route)
  },
  // 检测session_key
  checkSession(options) {
    const _this = this
    const sessionKey = wx.getStorageSync('sessionKey')
    const location = wx.getStorageSync('location')
    if (sessionKey) {
      const {
        lat,
        lng
      } = wx.getStorageSync('changeLocation')
      this.setData({
        longitude: lng,
        latitude: lat,
        markers: [{
          id: 1,
          latitude: lat,
          longitude: lng,
          title: '',
          zIndex: 1,
          iconPath: '/assets/images/center.png',
          width: 40,
          height: 40,
          callout: {
            content: '中心位置',
            color: '#000',
            fontSize: 12,
            borderRadius: 4,
            padding: 5
          },
        }]
      })
      if (options.index) {
        this.checkIndex(options)
      } else {
        this.getList(lat, lng)
      }
      return
    } else {
      login().then((res) => {
        return _getTokenSucc(res)
      }).then((res) => {
        return getUserInfoSucc(res)
      }).then((res) => {
        getLocation().then((e) => {
          const {
            lat,
            lng
          } = wx.getStorageSync('changeLocation')
          _this.setData({
            longitude: lng,
            latitude: lat,
            markers: [{
              id: 1,
              latitude: lat,
              longitude: lng,
              title: '',
              zIndex: 1,
              iconPath: '/assets/images/center.png',
              width: 40,
              height: 40,
              callout: {
                content: '中心位置',
                color: '#000',
                fontSize: 12,
                borderRadius: 4,
                padding: 5
              },
            }]
          })
          _this.getList(lat, lng)
        }).catch((res) => {
          const {
            lat,
            lng
          } = wx.getStorageSync('changeLocation')
          _this.setData({
            longitude: lng,
            latitude: lat,
            markers: [{
              id: 1,
              latitude: lat,
              longitude: lng,
              title: '',
              zIndex: 1,
              iconPath: '/assets/images/center.png',
              width: 40,
              height: 40,
              callout: {
                content: '中心位置',
                color: '#000',
                fontSize: 12,
                borderRadius: 4,
                padding: 5
              },
            }]
          })
          _this.getList(lat, lng)
        })
      }).catch((res) => {
        return false
      })
    }
  },
  checkIndex(options) {
    if (options.index) {
      this.setData({
        tableIndex: Number(options.index),
        tabIndex: Number(options.index),
        freedate: options.freedate || '',
        code: options.code || '',
        equipment: options.equipment || '',
        type: options.type || ''
      })
      if (options.equipment) {
        Number(options.index) === 0 ? this.classifySearchRent() : Number(options.index) === 1 ? this.classifySearchSell() : this.classifySearchMaintain()
      } else {
        const {
          lat,
          lng
        } = wx.getStorageSync('changeLocation')
        this.getList(lat, lng)
      }
    }
  },
  classifySearchRent() {
    const result = this.data.markers.slice(0, 1)
    const newInfo = []
    const {
      code,
      freedate
    } = this.data
    const {
      lat,
      lng
    } = wx.getStorageSync('changeLocation')
    const {
      userid
    } = wx.getStorageSync('userInfo')
    app.$api.index.rentFind({
      equtype: code,
      lon: lng,
      lat,
      userid,
      inqurystate: 0
    }).then((res) => {
      const data = res.data.data
      console.log(data)
      const free = this.data.freedate.split(',')
      console.log(free)
      if (data.length) {
        const info = data.filter((item) => {
          if (item.state === 2) {
            const freeItem = item.freedate.split(',')
            console.log(freeItem.length)
            if (free[0] !== '' && (free.length <= freeItem.length)) {
              const flag = free.map((subItem) => {
                return freeItem.includes(subItem)
              })
              if (flag.indexOf(false) < 0 && item.equtype === code) {
                console.log(flag, item)
                const iconPath = `../../assets/icon/${item.equtype}.png`
                result.push({
                  id: item.id,
                  latitude: item.lat,
                  longitude: item.lon,
                  title: '',
                  zIndex: 1,
                  iconPath: iconPath,
                  width: 46,
                  height: 50,
                  callout: {
                    content: item.equname,
                    color: '#000',
                    fontSize: 12,
                    borderRadius: 4,
                    padding: 5
                  },
                  anchor: {
                    x: 0,
                    y: 0
                  }
                })
                newInfo.push(this.calcDistance(item))
              } else {
                result.push(1)
              }
            } else if(item.equtype === code) {
              const iconPath = `../../assets/icon/${item.equtype}.png`
              result.push({
                id: item.id,
                latitude: item.lat,
                longitude: item.lon,
                title: '',
                zIndex: 1,
                iconPath: iconPath,
                width: 46,
                height: 50,
                callout: {
                  content: item.equname,
                  color: '#000',
                  fontSize: 12,
                  borderRadius: 4,
                  padding: 5
                },
                anchor: {
                  x: 0,
                  y: 0
                }
                
              })
              newInfo.push(this.calcDistance(item))
            } else {
              result.push(1)
            }
          }
        })
        console.log(info)
        result.indexOf(1) > 0 ? this.setData({
          list: []
        }) : this.setData({
          markers: result,
          list: newInfo
        })
      } else {
        this.setData({
          markers: result,
          list: []
        })
      }
    }).catch((res) => {
      toast('请稍后再试', 1000)
    })
    return false
  },
  classifySearchSell() {
    const result = this.data.markers.slice(0, 1)
    const newInfo = []
    const ents = []
    const {
      type,
      equipment,
      code
    } = this.data
    const {
      lat,
      lng
    } = wx.getStorageSync('changeLocation')
    const {
      userid
    } = wx.getStorageSync('userInfo')
    if (type === '') return
    console.log(type, equipment)
    app.$api.index.saleFind({
        entscope: code,
        lon: lng,
        lat,
        userid,
        inqurystate: 0
      })
      .then((res) => {
        const data = res.data.data
        data.filter((item) => {
          if (item.state === 2) {
            const iconPath = `../../assets/icon/${item.enttype}.png`
            if (item.enttype === type && item.entscope.indexOf(equipment) > -1) {
              result.push({
                id: item.id,
                latitude: item.lat,
                longitude: item.lon,
                title: '',
                zIndex: 1,
                iconPath: iconPath,
                width: 46,
                height: 50,
                callout: {
                  content: item.companyname,
                  color: '#000',
                  fontSize: 12,
                  borderRadius: 4,
                  padding: 5
                },
                anchor: {
                  x: 0,
                  y: 0
                }
              })
              app.$api.common.commonFindName({
                  code: item.enttype
                })
                .then((s) => {
                  const data = s.data
                  ents.push(data.name)
                  this.setData({
                    enterprise: ents
                  })
                }).catch((e) => {
                  toast('请稍后再试', 1000)
                })
              newInfo.push(this.calcDistance(item))
            }
          }
        })
        this.setData({
          markers: result,
          list: newInfo
        })
        // this.bindScrollTop()
      }).catch((e) => {
        toast('请稍后再试', 1000)
      })
  },
  classifySearchMaintain() {
    const result = this.data.markers.slice(0, 1)
    const {
      equipment
    } = this.data
    const newInfo = []
    const {
      userid
    } = wx.getStorageSync('userInfo')
    const {
      lat,
      lng
    } = wx.getStorageSync('changeLocation')
    if (equipment === '') return
    app.$api.index.maintainFind({
        maintainscope: '',
        lon: lng,
        lat,
        userid,
        inqurystate: 0
      })
      .then((res) => {
        const data = res.data.data
        data.filter((item, index) => {
          if (item.state === 2) {
            if (item.maintainscope.indexOf(equipment) > -1) {
              result.push({
                id: item.id,
                latitude: item.lat,
                longitude: item.lon,
                title: '',
                zIndex: 1,
                iconPath: '../../assets/icon/maintain.png',
                width: 46,
                height: 50,
                callout: {
                  content: item.companyname,
                  color: '#000',
                  fontSize: 12,
                  borderRadius: 4,
                  padding: 5
                },
                anchor: {
                  x: 0,
                  y: 0
                }
              })
              newInfo.push(this.calcDistance(item))
            }
          }
        })
        this.setData({
          markers: result,
          list: newInfo,
        })
        // this.bindScrollTop()
      }).catch((e) => {
        toast('请稍后再试', 1000)
      })
  },
  getList(lat, lng) {
    setTimeout(() => {
      wx.hideLoading()
    }, 2000)
    const index = this.data.tabIndex
    index === 0 ? this.getRent(lat, lng) : index === 1 ? this.getSell(lat, lng) : this.getMaintain(lat, lng)
  },
  getRent(lat, lng) {
    const result = this.data.markers.slice(0, 1)
    const newInfo = []
    const {
      userid
    } = wx.getStorageSync('userInfo')
    app.$api.index.rentFind({
        equtype: '',
        lon: lng,
        lat,
        userid,
        inqurystate: 0
      })
      .then((res) => {
        const data = res.data.data
        data.filter((item, index) => {
          if (item.state === 2) {
            const iconPath = `../../assets/icon/${item.equtype}.png`
            result.push({
              id: item.id,
              latitude: item.lat,
              longitude: item.lon,
              title: '',
              zIndex: 1,
              iconPath: iconPath,
              width: 46,
              height: 50,
              callout: {
                content: item.equname,
                color: '#000',
                fontSize: 12,
                borderRadius: 4,
                padding: 5
              },
              anchor: {
                x: 0,
                y: 0
              }
            })
            const info = this.calcDistance(item)
            newInfo.push(info)
          }
        })
        console.log(newInfo)
        this.setData({
          markers: result,
          list: newInfo
        })
        // this.bindScrollTop()
      }).catch((e) => {
        toast('请稍后再试', 1000)
      })
  },
  getSell(lat, lng) {
    const result = this.data.markers.slice(0, 1)
    const newInfo = []
    const ents = []
    const {
      userid
    } = wx.getStorageSync('userInfo')
    app.$api.index.saleFind({
        entscope: '',
        lon: lng,
        lat,
        userid,
        inqurystate: 0
      })
      .then((res) => {
        const data = res.data.data
        const info = data.filter((item, index) => {
          if (item.state === 2) {
            const iconPath = `../../assets/icon/${item.enttype}.png`
            result.push({
              id: item.id,
              latitude: item.lat,
              longitude: item.lon,
              title: '',
              zIndex: 1,
              iconPath: iconPath,
              width: 46,
              height: 50,
              callout: {
                content: item.companyname,
                color: '#000',
                fontSize: 12,
                borderRadius: 4,
                padding: 5
              },
              anchor: {
                x: 0,
                y: 0
              }
            })
            app.$api.common.commonFindName({
                code: item.enttype
              })
              .then((s) => {
                const data = s.data
                ents.push(data.name)
                this.setData({
                  enterprise: ents
                })
              }).catch((e) => {
                toast('请稍后再试', 1000)
              })
            const info = this.calcDistance(item)
            newInfo.push(info)
          }
        })
        this.setData({
          markers: result,
          list: newInfo
        })
        // this.bindScrollTop()
      }).catch((e) => {
        toast('请稍后再试', 1000)
      })
  },
  getMaintain(lat, lng) {
    const result = this.data.markers.slice(0, 1)
    const newInfo = []
    const {
      userid
    } = wx.getStorageSync('userInfo')
    app.$api.index.maintainFind({
        maintainscope: '',
        lon: lng,
        lat,
        userid,
        inqurystate: 0
      })
      .then((res) => {
        const data = res.data.data
        const info = data.filter((item, index) => {
          if (item.state === 2) {
            result.push({
              id: item.id,
              latitude: item.lat,
              longitude: item.lon,
              title: '',
              zIndex: 1,
              iconPath: '../../assets/icon/maintain.png',
              width: 46,
              height: 50,
              callout: {
                content: item.companyname,
                color: '#000',
                fontSize: 12,
                borderRadius: 4,
                padding: 5
              },
              anchor: {
                x: 0,
                y: 0
              }
            })
            const info = this.calcDistance(item)
            newInfo.push(info)
          }
        })
        this.setData({
          markers: result,
          list: newInfo,
        })
        // this.bindScrollTop()
      }).catch((e) => {
        toast('请稍后再试', 1000)
      })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    this.mapCtx = wx.createMapContext('map')
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    wx.removeStorageSync('router')
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 改变type
  handleChangeIndex(e) {
    const index = e.detail
    const {
      lat,
      lng
    } = wx.getStorageSync('changeLocation')
    this.setData({
      tabIndex: index
    })
    index === 0 ? this.getRent(lat, lng) : index === 1 ? this.getSell(lat, lng) : this.getMaintain(lat, lng)
  },
  // 跳转发布页
  bindPublish() {
    const index = this.data.tabIndex
    wx.navigateTo({
      url: `../publish/index?index=${index}`,
    })
  },
  // 个人中心
  bindPerson() {
    wx.navigateTo({
      url: '../../personal/person/index',
    })
  },
  // 详情页
  bindDetail() {
    wx.navigateTo({
      url: '../detail/index',
    })
  },
  // 分类页
  bindClassify() {
    const index = this.data.tabIndex
    wx.navigateTo({
      url: `../classify/index?index=${index}&entry=index`,
    })
  },
  bindMapChange(e) {
    this.getLatLng()
  },
  bindChange(e) {
    if (e.type === 'end') {
      this.getLatLng()
    }
  },
  getLatLng() {
    const _this = this
    this.mapCtx.getCenterLocation({
      success(res) {
        const {
          latitude,
          longitude
        } = res
        _this.setLngLat(latitude, longitude)
        wx.setStorageSync('changeLocation', {
          lat: latitude,
          lng: longitude
        })
      }
    })
  },
  setLngLat(lat, lng) {
    const _this = this
    const location = wx.getStorageSync('changeLocation')
    if (location) {
      this.mapCtx.translateMarker({
        markerId: 1,
        destination: {
          latitude: lat,
          longitude: lng
        },
        autoRotate: false,
        rotate: 0,
        duration: 1000,
        animationEnd() {
          wx.showLoading({
            title: '正在努力查找中...',
            mask: true,
            success() {
              _this.setData({
                ['markers[0].latitude']: lat,
                ['markers[0].longitude']: lng
              })
              _this.getList(lat, lng)
            }
          })
        },
        complete() {}
      })
    }
  },
  bindgLocation() {
    const location = wx.getStorageSync('location')
    this.setData({
      latitude: location.lat,
      longitude: location.lng
    })
    wx.setStorageSync('changeLocation', location)
    // this.getList(location.lat, location.lng)
  },
  bindDetail(e) {
    const {
      id
    } = e.currentTarget.dataset
    const {
      tabIndex
    } = this.data
    wx.navigateTo({
      url: `../../pages/detail/index?id=${id}&tabIndex=${tabIndex}`
    })
  },
  bindDetailCallout(e) {
    const id = e.markerId
    const {
      tabIndex
    } = this.data
    if (Number(e.markerId) === 1) {
      return
    }
    wx.navigateTo({
      url: `../../pages/detail/index?id=${id}&tabIndex=${tabIndex}`
    })
  },
  bindScrollTop() {
    const length = this.data.list.length
    if (length) {
      wx.getSystemInfo({
        success(e) {
          wx.pageScrollTo({
            scrollTop: e.windowHeight,
            duration: 500
          })
        }
      })
    }
  },
  calcDistance(item) {
    const locationA = {
      lat: Number(wx.getStorageSync('location').lat),
      lng: Number(wx.getStorageSync('location').lng)
    }
    const locationB = {
      lat: Number(item.lat),
      lng: Number(item.lon)
    }
    const distanceValue = distance(locationA, locationB)
    item = Object.assign({}, item, {
      distance: distanceValue
    })
    return item
  },
  bindRefresh(e) {
    wx.showLoading({
      title: '刷新中',
    })
    const {
      lat,
      lng
    } = wx.getStorageSync('changeLocation')
    this.getList(lat, lng)
    setTimeout(() => {
      wx.hideLoading()
    }, 2000)
  }
})